<template>
  <div class="container">
    <van-nav-bar title="工序检录入" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <van-button class="saveBtn" type="primary" native-type="submit" @click="submitForm">提交</van-button>
    <div class="publicBox">
      <div class="checkInputTop">
        <div class="checkInputTopCont">
          <ul>
            <li>
              <div>
                <b>工单号</b>
                <em><van-field v-model="detailsObj.workOrderNo" readonly size="mini" /></em>
              </div>
            </li>
            <li>
              <div>
                <b>送检数量</b>
                <em>
                  <van-cell-group>
                    <van-field v-model="detailsObj.reportNum" readonly size="mini" />
                  </van-cell-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>不合格数</b>
                <em>
                  <van-cell-group>
                    <van-field v-model="ruleForm.unqualifiedNum" :min="0" :formatter="formatter" type="number" placeholder="请输入数字" /></van-cell-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>合格数</b>
                <em>
                  <van-cell-group>
                    <van-field v-model="ruleForm.qualifiedNum" readonly size="mini" />
                  </van-cell-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>检验人</b>
                <em><van-field v-model="ruleForm.checkUserName" size="mini" readonly @click="showUser = true" /></em>
              </div>
            </li>
            <li>
              <div>
                <b>检验时间</b>
                <em>
                  <van-cell-group>
                    <van-field v-model="ruleForm.checkTime" size="mini" readonly @click="selectTime()" />
                  </van-cell-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>检验结果</b>
                <em>
                  <van-radio-group v-model="result" class="radioStyle" direction="horizontal" style="margin-top:15px ;">
                    <van-radio :name="1" shape="square">结果分开算</van-radio>
                    <van-radio :name="2" shape="square">整批合格</van-radio>
                    <van-radio :name="3" shape="square">整批不合格</van-radio>
                  </van-radio-group>
                </em>
              </div>
            </li>
            <li>
              <div>
                <b>不合格原因</b>
                <em><van-field v-model="ruleForm.unqualifiedReason" size="mini" /></em>
              </div>
            </li>
            <li>
              <div>
                <b>备注</b>
                <em><van-field v-model="ruleForm.remark" size="mini" /></em>
              </div>
            </li>
            <li>
              <div class="liDiv">
                <b>附件上传</b>
                <em>
                  <van-uploader v-model="ruleForm.patrolFileList" multiple :max-count="5" :after-read="afterRead()" :max-size="5242880" accept="image/jpeg ,image/png" @oversize="onOversize">
                    <van-button round type="info">上传图片</van-button>
                  </van-uploader>
                </em>
              </div>
            </li>

          </ul>
        </div>
      </div>
      <div class="qualityContent">
        <h1>质量控点</h1>
        <div class="contentItem">
          <!-- 质量控点 -->
          <quality-control ref="qualityControl" :item-list="ruleForm.itemList" :itooles-list="itooles" />
        </div>
      </div>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="datetime" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 人员选择 -->
    <van-popup v-model="showUser" position="bottom" :style="{ height: '30%' }">
      <van-picker title="人员选择" show-toolbar :columns="userList" @confirm="onConfirm" @cancel="showUser = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction } from '../../../../utils/function'
import qualityControl from '../../component/qualityControlPre'
export default {
  name: 'FirstInspection',
  components: { qualityControl },
  data () {
    return {
      currentDate: new Date(),
      userList: [],
      itemList: [],
      ruleForm: {
        patrolFileList: [],
        unqualifiedReason: '',
        itemList: [],
        result: null,
        qualifiedNum: null,
        unqualifiedNum: 0,
        remark: null,
        checkUserName: JSON.parse(localStorage.getItem('padUserInfo')).data.userName, // 检验人
        checkTime: myFunction(new Date()), // 检验时间
        checkUserId: JSON.parse(localStorage.getItem('padUserInfo')).data.userId // 本次检验
      },
      show: false,
      code: localStorage.getItem('code'),
      search: {
        current: 1,
        size: 5
      },
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      disabledResult: false,
      showTime: false,
      showUser: false,
      itooles: [],
      checkValList: [],
      result: 1
    }
  },
  watch: {
    ruleForm: {
      handler (row) {
        row.reportNum = this.detailsObj.reportNum
        row.qualifiedNum = Number(this.detailsObj.reportNum) - Number(row.unqualifiedNum)
        if (Number(row.unqualifiedNum) > 0) {
          this.$nextTick(() => {
            this.result = 3
          })
        }
        if (Number(row.unqualifiedNum) > row.reportNum) {
          this.$toast.fail('不合格数>送检数量，请核实！')
          row.unqualifiedNum = 0
          row.qualifiedNum = 0
        }
      },
      deep: true,
      immediate: true
    }
  },
  created () {
    // this.search.proBatchNo = this.$route.query.code
  },
  mounted () {
    this.getData()
  },
  methods: {
    async getData (row) {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '数据加载中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.detailsObj = this.$store.state.data
      /* 获取人员 */
      await this.getUser()
      await this.getToolList()
      await this.getItemList(toast)
    },
    // 获取所有检验工具
    async getToolList () {
      const res = await this.$axios.post('/dobo-product/qm/check/tool/listByStatus')
      if (res.data.code === 200) {
        this.itooles = res.data.data
        this.itooles.forEach(item => {
          item.toolId = item.id
        })
      }
    },
    /* 获取所有人员 */
    async getUser () {
      const res = await this.$axios.get('/dobo-user/user/getAllUser')
      if (res.data.code === 200) {
        this.userLists = res.data.data
        res.data.data.forEach(item => {
          this.userList.push(item.name)
        })
      }
    },
    /* 获取质量控点 */
    async getItemList (toast) {
      const res = await this.$axios.get(`/dobo-product/pad/patrol/getItemList?bomId=${this.detailsObj.bomId}&materialId=${this.detailsObj.materialId}&procedureCode=${this.detailsObj.procedureCode}&routeId=${this.detailsObj.routeId}`)
      if (res.data.code === 200) {
        if (res.data.data.length < 1) {
          setTimeout(() => {
            toast.clear()
          }, 100)
          this.$dialog.alert({
            title: '提示',
            message: '当前数据没有质量控点请维护质量控点！'
          }).then(() => {
            this.$router.go(-1)
          })
          return
        } else {
          setTimeout(() => {
            toast.clear()
            res.data.data.forEach(item => {
              item.result = null
              item.tool = []
              item.unqualifiedNum = 0
              item.checkVals = [
                {
                  name: '检验值',
                  val: ''
                }
              ]
              if (item.toolId) {
                item.itemToolEntityList = []
                this.itooles.forEach(itx => {
                  if (itx.toolId === item.toolId) {
                    item.tool.push(itx.toolId)
                    item.itemToolEntityList.push(itx)
                    delete itx.id
                  }
                })
              }
            })
            this.ruleForm.itemList = res.data.data
          }, 10)
        }
      }
    },
    onOversize (file) {
      this.$toast.fail('文件大小不能超过 5M')
    },
    // 上传图片
    afterRead (items, type) {
      return file => {
        if (file) {
          if (file.constructor === Object) file = [file]
          const toast = this.$toast.loading({
            duration: 0, // 持续展示 toast
            message: '图片上传中...',
            forbidClick: true,
            loadingType: 'spinner'
          })
          file.filter((item, index) => {
            const form = new FormData()
            form.append('file', item.file)
            this.$axios.post('/dobo-file/files-anon', form).then(res => {
              if (res.data.code === 200) {
                item.fileId = res.data.data.id
                item.fileUrl = res.data.data.url
                item.fileName = res.data.data.name
                if (++index === file.length) {
                  toast.clear()
                }
              } else {
                this.$toast.fail(res.data.msg)
                toast.clear()
              }
            })
          })
        }
      }
    },
    /* 选择时间 */
    selectTime () {
      this.showTime = true
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      this.ruleForm.checkTime = myFunction(value)
      this.showTime = false
    },
    /* 人员选择 */
    onConfirm (e) {
      let id = ''
      this.userLists.forEach(item => {
        if (item.name === e) id = item.id
      })
      this.ruleForm.checkUserId = id
      this.ruleForm.checkUserName = e
      this.showUser = false
    },
    /** 验证检验数量只可输入大于等于0 的整数 */
    formatter (value) {
      if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(/[^0-9]/g, '') : 0
      } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(/[^0-9]/g, '') : 0
      } else {
        return 0
      }
    },
    sum (arr) {
      return arr.reduce(function (prev, curr, idx, arr) {
        return prev + curr
      })
    },
    submitForm () {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否确认提交？'
        })
        .then(() => {
          this.ruleForm.itemList.forEach(item => {
            if (item.itemFileEntityList) {
              item.itemFileEntityList.forEach(itx => delete itx.content)
            }
            delete item.toolId
            delete item.tool
            if (item.unqualifiedNum === '') item.unqualifiedNum = 0

            this.checkValList = []
            if (item.checkVals) {
              item.checkVals.forEach(itx => {
                if (itx.val) {
                  this.checkValList.push(itx.val)
                }
              })
              item.checkVal = this.checkValList.toString()
            }
          })
          this.submitApi()
        })
        .catch(() => {
          return false
        })
    },
    submitApi () {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      this.ruleForm.result = this.result
      this.ruleForm.reportId = this.detailsObj.id
      this.$axios.post('/dobo-product/pad/procedure/save', this.ruleForm).then(res => {
        if (res.data.code === 200) {
          toast.clear()
          this.$dialog
            .alert({
              title: '提示',
              message: '提交成功!'
            })
            .then(() => {
              this.$router.push('/processInspection')
            })
            .catch(() => {})
        } else {
          this.$toast.fail(res.data.msg)
          setTimeout(() => {
            toast.clear()
            this.$router.push('/processInspection')
          }, 1000)
        }
      }).catch(() => {
      })
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/processInspection')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container{
  .checkInputTopCont{
    ul{
      li:first-child{
        width: 100% !important;
        .van-cell{
          width: 98% !important;
        }
      }
      li:nth-child(6),li:nth-child(7),li:nth-child(8),li:nth-child(9),li:nth-child(10){
        width: 100% !important;
        .van-cell{
          width: 98% !important;
        }
      }
      .liDiv{
        .van-button{
          height: 45px;
          font-size: 20px !important;
        }
      }
    }
  }
  .qualityContent{
    height: calc(100% - 405px);
    overflow: hidden;
    h1{
      height: 40px;
      line-height: 40px;
      font-weight: normal;
      text-align: center;
      background: #eeee;
      color: #022566;
    }
    .contentItem{
      height: calc(100% - 40px);
      overflow-y: auto;
    }
  }
}
</style>
<style lang='scss'>

</style>
